<template>
  <div class="app-container">
    <div class="top">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="68px"
      >
        <el-form-item>
          <el-checkbox
            v-model="queryParams.queryType"
            label="与我相关"
            border
            size="small"
            true-label="user"
            false-label="workshop"
            class="related-me"
            @change="handleQuery"
          ></el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-checkbox
            v-model="queryParams.queryQcTask"
            label="品控关注"
            border
            size="small"
            true-label="1"
            false-label=""
            class="related-me"
            @change="handleQuery"
          ></el-checkbox>
        </el-form-item>
        <el-form-item prop="taskName" class="width1">
          <el-input
            v-model="queryParams.taskName"
            placeholder="请输入关键字"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item class="width1"> -->
        <organizationCascader
          class="organization-cascader"
          :clearData="{
            factory: true,
            workshop: true,
            line: true,
          }"
          :arrData="queryParams"
          :showData="{
            factory: true,
            workshop: true,
            line: true,
            workSection: false,
          }"
          :isAllList="true"
          @change="queryParamsChange"
        ></organizationCascader>
        <!-- </el-form-item> -->
        <el-form-item prop="taskType" class="width1">
          <el-select
            v-model="queryParams.taskType"
            placeholder="请选择任务类型"
            clearable
            size="small"
          >
            <el-option
              v-for="item in dict.taskType"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="status" class="width1">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            size="small"
          >
            <el-option
              v-for="item in taskStatusOptions"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
            <el-option key="timeout" label="超时时长>0" value="timeout">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="time" class="width2">
          <el-date-picker
            v-model="queryParams.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
            value-format="yyyy-MM-dd HH:mm:ss"
            align="right"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <div class="operate">
        <el-button
          type="default"
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['taskMgmt:history:export']"
          >导出
        </el-button>
      </div>
    </div>
    <el-table
      ref="Table"
      :data="list"
      tooltip-effect="dark"
      style="width: 100%"
      height="calc(100% - 88px - 50px)"
      v-loading="loading"
    >
      <el-table-column label="任务ID" prop="id"> </el-table-column>
      <el-table-column label="任务名称" prop="taskName">
        <template slot-scope="{ row }">
          <el-button type="text" @click.stop="handleDetail(row)">{{
            row.taskName
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="任务类型" prop="taskType" width="140">
        <template slot-scope="{ row }">
          {{ taskTypeDictObj[row.taskType] }}
        </template>
      </el-table-column>
      <el-table-column label="品控关注" prop="isConcernedTask">
        <template slot-scope="{ row }">
          {{ row.isConcernedTask == "1" ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="车间" prop="ownedWorkshopName"> </el-table-column>
      <el-table-column label="产线" prop="ownedProductionLineName" width="160">
      </el-table-column>
      <el-table-column label="执行人">
        <template slot-scope="{ row }">
          {{ getOperatorLabel(row) }}
        </template>
      </el-table-column>
      <el-table-column label="审核人" prop="auditorName">
        <!-- <template slot-scope="{ row }">
          {{ postManageDictObj[row.auditor] || row.auditorName }}
        </template> -->
      </el-table-column>
      <el-table-column label="当前班组" prop="groupName" width="130"></el-table-column>
      <el-table-column label="任务时间" width="160">
        <template slot-scope="{ row }">
          <div>{{ row.actualExecuteStartTime + " - " }}</div>
          <div>{{ row.actualExecuteEndTime }}</div>
        </template>
      </el-table-column>
      <el-table-column label="超时时长(小时)">
        <template slot-scope="{ row }">
          {{ row.taskTimeoutHour ? row.taskTimeoutHour + "小时" : "" }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="{ row }">
          <span :class="'status-' + row.status">{{
            taskStatusDictObj[row.status]
          }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="pager.total"
      :page.sync="pager.pageNum"
      :limit.sync="pager.pageSize"
      @pagination="getList"
    />

    <!-- 任务详情 -->
    <DetailDialog
      :visible.sync="detailDailog.visible"
      :row="detailDailog.row"
    ></DetailDialog>
  </div>
</template>
<script>
import organizationCascader from "@/views/components/organizationCascader";
import { getTaskCenterList, exportTaskList } from "@/api/taskMgmt/center";
import DetailDialog from "../center/detailDialog";
import { downloadFile } from "@/utils/file";
import { mapState,mapMutations } from "vuex";
// 历史任务列表展示的所有状态(已完成，已关闭)
const AllStatus = ["4", "6"];
export default {
  name: "TaskHistory",
  components: {
    organizationCascader,
    DetailDialog,
  },
  dicts: ["taskType","taskStatus","PostManage"],
  data() {
    return {
      queryParams: {
        taskName: "",
        factoryDeptCode: "",
        workshopCode: "",
        lineCode: "",
        lineId: "",
        taskType: "",
        status: "",
        time: null,
        queryType: "user", //默认与我相关
        queryQcTask: "",
      },
      list: [],
      loading: false,
      pager: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
      },
      detailDailog: {
        visible: false,
        row: null,
      },
      exportLoading: false,
    };
  },
  computed: {
    ...mapState({
      taskHisDetail:(state) => state.workbench.taskHisDetail
    }),
    taskStatusOptions() {
      if (!this.dict.taskStatus) {
        return [];
      }
      // 只展示已超时，已完成，已关闭
      return this.dict.taskStatus.filter((ele) =>
        AllStatus.includes(ele.codevalue)
      );
    },
    taskTypeDictObj() {
      return this.dictToMap(this.dict.taskType);
    },
    taskStatusDictObj() {
      return this.dictToMap(this.dict.taskStatus);
    },
    postManageDictObj() {
      return this.dictToMap(this.dict.PostManage);
    },
  },
  activated(){
    if(this.taskHisDetail){
      this.queryParams = Object.assign({},this.queryParams,this.taskHisDetail)
      this.getList();
    }
  },

  deactivated() {
    this.SET_TASKHIS_DETAIL(null)
  },

  created() {
    // 默认获取第一个工厂-车间-产线
    const results = this.getOwnFirstLine();
    this.queryParams.factoryDeptCode = results[0]?.factoryDeptCode || "";
    this.queryParams.workshopCode = results[1]?.workshopCode || "";
    this.queryParams.lineCode = results[2]?.lineCode || "";
    this.queryParams.lineId = results[2]?.lineId || "";
    if(this.taskHisDetail){
      this.queryParams = Object.assign({},this.queryParams,this.taskHisDetail)
    }
    //获取列表数据
    this.getList();
  },
  methods: {
    ...mapMutations("workbench", ["SET_TASKHIS_DETAIL"]),
    getList() {
      this.loading = true;
      const { pageNum, pageSize } = this.pager;
      const {
        taskName,
        factoryDeptCode,
        workshopCode,
        lineCode,
        taskType,
        status,
        time,
        queryType,
        queryQcTask,
      } = this.queryParams;
      const params = {
        query: {
          taskName,
          ownedFactory: factoryDeptCode,
          ownedWorkshop: workshopCode,
          ownedProductionLine: lineCode,
          taskType,
          statusList: status
            ? status == "timeout"
              ? [...AllStatus, status]
              : [status]
            : AllStatus,
          actualExecuteStartTime: time?.length ? time[0] : "",
          actualExecuteEndTime: time?.length ? time[1] : "",
          queryType,
          queryQcTask,
        },
        pageNum,
        pageSize,
      };
      getTaskCenterList(params)
        .then((res) => {
          this.list = res.rows || [];
          this.pager.total = res.total;
          this.loading = false;
        })
        .catch(() => {
          this.list = [];
          this.pager.total = 0;
          this.loading = false;
        });
    },
    getOperatorLabel(row) {
      if (row.operatorType == "dept") {
        // 显示部门
        return row.executiveAgencyName || row.executiveAgency;
      }

      let operatorName = row.operatorName;

      // if (this.postManageDictObj.hasOwnProperty(row.operator)) {
      //   // 显示岗位
      //   operatorName = this.postManageDictObj[row.operator];
      // } else {
      //   // 显示工位
      //   operatorName = row.operatorName;
      // }

      return operatorName || "";
    },
    queryParamsChange({ factoryDeptCode, workshopCode, lineCode, lineId }) {
      this.queryParams.factoryDeptCode = factoryDeptCode;
      this.queryParams.workshopCode = workshopCode;
      this.queryParams.lineCode = lineCode;
      this.queryParams.lineId = lineId;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pager.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        taskName: "",
        factoryDeptCode: "",
        workshopCode: "",
        lineCode: "",
        lineId: "",
        taskType: "",
        status: "",
        time: null,
        queryType: "user", //默认与我相关
        queryQcTask: "",
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleDetail(row) {
      this.detailDailog.row = row;
      this.detailDailog.visible = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.exportLoading = true;

      const {
        taskName,
        factoryDeptCode,
        workshopCode,
        lineCode,
        taskType,
        status,
        time,
        queryType,
        queryQcTask,
      } = this.queryParams;
      const params = {
        taskName,
        ownedFactory: factoryDeptCode,
        ownedWorkshop: workshopCode,
        ownedProductionLine: lineCode,
        taskType,
        statusList: status
          ? status == "timeout"
            ? [...AllStatus, status]
            : [status]
          : AllStatus,
        actualExecuteStartTime: time?.length ? time[0] : "",
        actualExecuteEndTime: time?.length ? time[1] : "",
        queryType,
        queryQcTask,
      };
      exportTaskList(params)
        .then((res) => {
          downloadFile(
            res.file,
            res.name ||
              `任务历史列表${this.parseTime(new Date(), "{y}{m}{d}")}.xlsx`
          );
        })
        .finally(() => {
          this.exportLoading = false;
        });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .top {
  height: 88px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  .width1 {
    .el-form-item__content {
      width: 142px;
    }
  }
  .width2 {
    .el-date-editor--datetimerange.el-input__inner {
      width: 360px;
    }
  }
  .el-form {
    width: 100%;
    text-align: right;
    height: 53px;
  }
}
::v-deep .organization-cascader {
  display: inline-block;
  vertical-align: middle;
  color: #cccccc;
  .el-form-item {
    margin-bottom: 0;
    .el-form-item__content {
      width: 142px;
    }
  }
}
.pagination-container {
  margin: 0;
}
</style>
